import axios from 'axios'
export default {
  namespaced: true,
  state () {
    return {
      cartList: []
    }
  },
  getters: {
    totalPrice (state) {
      return state.cartList.reduce((sum, v) => (sum += v.price * v.count), 0)
    },

    totalCount (state) {
      return state.cartList.reduce((sum, v) => (sum += v.count), 0)
    }
  },
  mutations: {
    setCartList (state, list) {
      state.cartList = list
    },

    changeCount () {
      console.log('mutation的changeCount')
      // // 根据id先找到对应的那个元素
      // const item = state.cartList.find(v => v.id === obj.id)
      // // 修改数量
      // item.count = obj.count
    }
  },
  actions: {
    async reqCartList (ctx) {
      // 发请求
      const res = await axios({
        url: 'http://localhost:3000/cart'
      })
      ctx.commit('setCartList', res.data)
    },

    // 要传递一个对象过来，对象里要包含id和要修改的数量
    async changeCount () {
      console.log('action的changeCount')
      //  await axios({
      //   url: `http://localhost:3000/cart/${obj.id}`,
      //   method: 'patch',
      //   data: {
      //     count: obj.count
      //   }
      // })

      // // 发完请求立即改界面-其实就是改到state
      // ctx.commit('changeCount', obj)
    }
  }
}
